from flask import Flask, request, jsonify
import logging
import sys

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger(__name__)

app = Flask(__name__)

@app.route('/api/endgame', methods=['POST', 'GET'])  # 支持POST和GET请求
def handle_endgame_callback():
    try:
        logger.info(f"Received request to /api/endgame with method {request.method}")
        if request.method == 'POST':
            if request.is_json:
                data = request.get_json()
                # 这里添加具体的业务逻辑处理，如解析数据、更新数据库、调用其他服务等
                # 示例：假设回调数据包含用户ID和状态信息
                user_id = data.get('user_id')
                status = data.get('status')
                logger.info(f"Received callback for user {user_id} with status {status}")
            else:
                # 如果不是JSON格式，尝试从表单或原始数据读取
                logger.warning("Request is not JSON format, attempting to parse form data")
                data = request.form.to_dict() or {}
                if not data and request.data:
                    logger.warning("Attempting to parse raw data")
                    try:
                        from urllib.parse import parse_qs
                        data = parse_qs(request.data.decode('utf-8'))
                    except Exception as e:
                        logger.error(f"Failed to parse raw data: {str(e)}")
            
            return jsonify({"message": "Callback received and processed successfully"}), 200
        else:  # GET请求
            return jsonify({"message": "Endgame callback endpoint is ready"}), 200
    except Exception as e:
        logger.error(f"Error processing callback: {str(e)}")
        return jsonify({"error": str(e)}), 500

# 添加健康检查路由
@app.route('/', methods=['GET'])
@app.route('/health', methods=['GET'])
def health_check():
    logger.info("Health check request received")
    return jsonify({"status": "ok"}), 200

# 添加主程序入口点
if __name__ == '__main__':
    logger.info("Starting Flask application")
    app.run(host='0.0.0.0', port=8000, debug=True)